package org.microservice.common.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/7/27
 * Time: 13:16
 * To change this template use File | Settings | File Templates.
 * Description:
 */
public class ZipUtil {

    public static byte[] createZip(String sourcePath) throws Exception{

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //将目标文件打包成zip导出
        File file = new File(sourcePath);
        writeZip(zip,file,"");
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();

    }

    private static void writeZip(ZipOutputStream zip,File file, String parentPath ) throws Exception {
        if (file.exists()) {
            if (file.isDirectory()) {//处理文件夹
                File[] files = file.listFiles();
                parentPath += file.getName() + File.separator;
                if (files.length != 0) {
                    for (File f : files) {
                        writeZip(zip,f, parentPath);
                    }
                } else {       //空目录则创建当前目录
                    zip.putNextEntry(new ZipEntry(parentPath));
                }
            } else {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                ZipEntry entry = new ZipEntry(parentPath+file.getName());
                zip.putNextEntry(entry);

                zip.write(FileUtils.readFileToByteArray(file));
                IOUtils.closeQuietly(bis);
                zip.flush();
                zip.closeEntry();

            }
        }
    }


}
